<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}学员列表</div>
    <div class="table-operator">
      <div style="margin-bottom:10px">
        <a-button type="primary" @click="handleExport">导出数据</a-button>
        <a-button type="primary" @click="handleExportAvatar" style="margin-left:10px">导出头像</a-button>
      </div>
      <a-row :gutter="10">
        <a-form :layout="formLayout" labelAlign="left" :form="searchForm" @submit="handleSubmit">
          <a-col :span="6">
            <a-form-item label="学员姓名" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input

                placeholder="请输入学员姓名"
                v-decorator="['name']"
              />
            </a-form-item>

            <a-form-item label="考试时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-range-picker
                format="YYYY-MM-DD"
                v-decorator="['create_time']"
              />
            </a-form-item>


            <!--            <a-form-item label="工种" :label-col="labelCol" :wrapper-col="wrapperCol">-->
            <!--              <a-input-->
            <!--                placeholder="请输入工种"-->
            <!--                v-decorator="['subject']"-->
            <!--              />-->
            <!--            </a-form-item>-->
          </a-col>
          <a-col :span="6">
            <a-form-item label="手机号码" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input
                placeholder="请输入手机号码"
                v-decorator="['phone']"
              />
            </a-form-item>
            <a-form-item :label-col="labelCol" :wrapper-col="{ style: 'width: 100%;float:left' }">
              <a-button type="primary" html-type="submit" icon="search">点击搜索</a-button>
              <a-button style="margin-left:10px" @click="handleReset">重置表单</a-button>
            </a-form-item>
            <!--            <a-form-item label="工种等级" :label-col="labelCol" :wrapper-col="wrapperCol">-->
            <!--              <a-input-->
            <!--                placeholder="请输入工种等级"-->
            <!--                v-decorator="['subject_level']"-->
            <!--              />-->
            <!--            </a-form-item>-->
          </a-col>
          <a-col :span="6">
            <a-form-item label="身份证号" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-input
                placeholder="请输入身份证号"
                v-decorator="['idnumber']"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="用户" :label-col="labelCol" :wrapper-col="wrapperCol">
              <a-tree-select
                v-decorator="['channel_id']"
                :treeData="userList"
                :replaceFields="{children:'children', title:'real_name', key:'store_user_id', value: 'store_user_id' }"
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                placeholder="请选择用户"
                allow-clear
                tree-default-expand-all
              >
              </a-tree-select>
            </a-form-item>
            <!--            <a-form-item label='考试成绩' :label-col='labelCol' :wrapper-col='wrapperCol'>-->
            <!--              <a-select-->
            <!--                allowClear-->
            <!--                placeholder='请选择考试成绩'-->
            <!--                v-decorator="['score']"-->
            <!--              >-->
            <!--                <a-select-option :value='0'>及格</a-select-option>-->
            <!--                <a-select-option :value='1'>不及格</a-select-option>-->
            <!--              </a-select>-->
            <!--            </a-form-item>-->


          </a-col>
        </a-form>
      </a-row>
    </div>
    <s-table
      ref="table"
      rowKey="student_id"
      :loading="isLoading"
      :columns="columns"
      :data="loadData"
      :pageSize="15"
      tableLayout="auto"
      :scroll="{x:true}"
    >
      <div slot="name" slot-scope="text, item">
        {{ text }}
        <a-tag v-if="item.is_cancel==1 && score==1" color="red">已标记无效考试</a-tag>
      </div>
      <div slot="sign_url" slot-scope="text, item">
        <a :href="text" target="_blank"><img :src="text" style="height:60px"></a>
      </div>
      <div slot="score" slot-scope="text, item">
        <a v-if="text>=60" style="font-weight: 600;font-size: 20px;margin-right: 10px">{{ text }}</a>
        <a v-else style="font-weight: 600;font-size: 20px;margin-right: 10px;color: red">{{ text }}</a>
        <a-tag color="green" v-if="text>=60">及格</a-tag>
        <a-tag color="red" v-else>不及格</a-tag>
      </div>
      <div slot="qds" slot-scope="text, item">
        <template v-if="item.is_edit==false">
          <a v-if="currentUser.new_super==1" @click="item.is_edit=true">{{ text }}</a>
          <span v-else>{{ text }}</span>
        </template>
        <template v-else>
          <a-tree-select
            v-if="item.is_edit"
            v-model="item.channelInfo.store_user_id"
            :treeData="userList"
            :replaceFields="{children:'children', title:'real_name', key:'store_user_id', value: 'store_user_id' }"
            style="width: 100px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择用户"
            tree-default-expand-all
            @change="updateChannel($event,item)"
          />
          <a @click="item.is_edit=false"> 取消</a>
        </template>
      </div>
      <div slot="avatar_url" slot-scope="text, item">
        <a :href="text" target="_blank"><img :src="text" style="height:60px"></a>
      </div>
      <div class="actions" slot="action" slot-scope="text, item">
        <template>
          <a v-if="!item.is_cancel" @click="handleCancel(item)">{{ item.is_cancel ? '还原' : '标记无效考试' }}</a>
          <!--                    <a v-action:delete @click="handleDelete(item)">删除</a>-->
        </template>
      </div>
    </s-table>
  </a-card>
</template>
<script>
import * as Api from '@/api/student'
import * as userApi from '@/api/store/user'

import { STable, UploadImage } from '@/components'

const columns1 = [
  {
    title: '学员ID',
    dataIndex: 'student_id'
  },
  {
    title: '考试头像',
    dataIndex: 'face_file.external_url',
    scopedSlots: { customRender: 'avatar_url' }
  },
  {
    title: '承诺签名',
    dataIndex: 'comsign_file.external_url',
    scopedSlots: { customRender: 'sign_url' }
  },
  {
    title: '交卷签名',
    dataIndex: 'examsign_file.external_url',
    scopedSlots: { customRender: 'sign_url' }
  },
  {
    title: '学员姓名',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '身份证号',
    dataIndex: 'idnumber'
  },
  {
    title: '手机号码',
    dataIndex: 'phone'
  },
  {
    title: '工种',
    dataIndex: 'subject.subject_name'
  },
  {
    title: '工种等级',
    dataIndex: 'subject_level.level_name'
  },
  {
    title: '考试成绩',
    dataIndex: 'score',
    scopedSlots: { customRender: 'score' }
  },
  {
    title: '考试时间',
    dataIndex: 'create_time'
  },
  {
    title: '用户',
    dataIndex: 'channelInfo.real_name',
    scopedSlots: { customRender: 'qds' }
  },
  {
    fixed: 'right',
    title: '操作',
    dataIndex: 'action',
    width: '100px',
    scopedSlots: { customRender: 'action' }
  }
]
const columns2 = [
  {
    title: '学员ID',
    dataIndex: 'student_id'
  },
  {
    title: '考试头像',
    dataIndex: 'face_file.external_url',
    scopedSlots: { customRender: 'avatar_url' }
  },
  {
    title: '承诺签名',
    dataIndex: 'comsign_file.external_url',
    scopedSlots: { customRender: 'sign_url' }
  },
  {
    title: '交卷签名',
    dataIndex: 'examsign_file.external_url',
    scopedSlots: { customRender: 'sign_url' }
  },
  {
    title: '学员姓名',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '身份证号',
    dataIndex: 'idnumber'
  },
  {
    title: '手机号码',
    dataIndex: 'phone'
  },
  {
    title: '工种',
    dataIndex: 'subject.subject_name'
  },
  {
    title: '工种等级',
    dataIndex: 'subject_level.level_name'
  },
  {
    title: '考试成绩',
    dataIndex: 'score',
    scopedSlots: { customRender: 'score' }
  },
  {
    title: '考试时间',
    dataIndex: 'create_time'
  },
  {
    title: '用户',
    dataIndex: 'channelInfo.real_name',
    scopedSlots: { customRender: 'qds' }
  }
]

export default {
  name: 'Index',
  props: {
    score: {
      type: Number,
      required: true
    }
  },
  components: {
    STable,
    UploadImage
  },
  data () {
    return {
      currentUser: this.$store.getters.userInfo,
      searchForm: this.$form.createForm(this),
      formLayout: 'horizontal',
      labelCol: {
        style: 'width: 70px;float:left;margin-right:10px;white-space: nowrap;\n' +
          'text-overflow: ellipsis;\n' +
          '-o-text-overflow: ellipsis;\n' +
          'overflow: hidden;'
      },
      wrapperCol: { style: 'width: calc( 95% - 70px );float:left' },
      codeUrl: '',
      // 角色列表
      roleList: [],
      // 查询参数
      queryParam: {
        score: this.score
      },
      // 正在加载
      isLoading: false,
      // 表头
      columns: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: param => {
        return Api.list({ ...param, ...this.queryParam })
          .then(response => {
            response.data.list.data.forEach(item => {
              item.is_edit = false
            })
            return response.data.list
          })
      },
      userList: []
    }
  },
  created () {
    if (this.score == 1) {
      this.columns = columns1
    } else {
      this.columns = columns2
    }

    this.getUserTreeList()
  },
  methods: {
    async updateChannel (channel_id, item) {
      await Api.edit({ student_id: item.student_id, form: { channel_id } })
      this.$message.success('修改成功', 1.5)
      this.handleRefresh()
    },

    getUserTreeList () {
      userApi.getUserTreeList().then(({ data: { list } }) => {
        this.userList = list
      })
    },
    handleSubmit (e) {
      e.preventDefault()
      const { searchForm: { validateFields } } = this
      validateFields((errors, values) => {
        if (errors) {
          return false
        }
        this.queryParam = { ...this.queryParam, ...values }
        this.handleRefresh(true)
      })
    },
    handleReset () {
      this.searchForm.resetFields()
    },

    handleExport () {
      const params = { ...this.searchForm.getFieldsValue(), ...this.queryParam }
      if (params.create_time) {
        params.create_time = params.create_time[0].format('YYYY-MM-DD') + '/' + params.create_time[1].format('YYYY-MM-DD')
      }
      Api.exportExcel({ ...params, ...{ export: 1 } })
    },
    handleExportAvatar () {
      const params = { ...this.searchForm.getFieldsValue(), ...this.queryParam }
      if (params.create_time) {
        params.create_time = params.create_time[0].format('YYYY-MM-DD') + '/' + params.create_time[1].format('YYYY-MM-DD')
      }
      Api.exportAvatar({ ...params }).then(({ data: { url } }) => {
        window.open(url)
      })
    },
    /**
     * 新增记录
     */
    handleAdd () {
      // this.$refs.AddForm.add()
    },

    /**
     * 编辑记录
     */
    handleEdit (item) {
      // this.$refs.EditForm.edit(item)
    },

    handleCancel (item) {
      Api.edit({ studentId: item['student_id'], form: { is_cancel: item['is_cancel'] ? 0 : 1 } })
        .then((result) => {
          this.handleRefresh()
        })
    },
    /**
     * 删除记录
     */
    handleDelete (item) {
      const app = this
      const modal = this.$confirm({
        title: '您确定要删除该记录吗?',
        content: '删除后不可恢复',
        onOk () {
          return Api.deleted({ studentId: item['student_id'] })
            .then((result) => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally(result => {
              modal.destroy()
            })
        }
      })
    },

    /**
     * 刷新列表
     * @param Boolean bool 强制刷新到第一页
     */
    handleRefresh (bool = false) {
      this.$refs.table.refresh(bool)
    },

    /**
     * 检索查询
     */
    onSearch () {
      this.handleRefresh(true)
    }
  }
}
</script>
